import React, { useState } from 'react';
import editIcon from '../../../assets/images/edit.png';
import { getDynamicFonts } from '@/utils/fontUtils';
import { useTranslation } from 'react-i18next';
import dj1 from '@/assets/images/ptVip.png'// 等级一的头像装饰
import dj2 from '@/assets/images/xyVip.png'// 等级一的头像装饰
import dj3 from '@/assets/images/zzVip.png'// 等级一的头像装饰
import PhoneInput from 'react-phone-input-2';
import 'react-phone-input-2/lib/style.css';
import { updateUserInformation, updateUserPassword } from '@/api/userService';
import { message } from 'antd';
import AvatarUploadModal from './AvatarUploadModal';
import { useUserProfile } from '@/hooks/useUserProfile';
interface ProfileSettingsProps {
    avatar?: string;
    displayName?: string;
    gender?: string;
    email?: string;
    phone?: string;
    tokensBalance?: string;
    membershipTier?: number; // Added membershipTier to props
    onProfileUpdated?: () => void; // 新增
}

// 编辑弹窗组件
const EditModal = ({
    open,
    onClose,
    onConfirm,
    field,
    value,
    options
}: {
    open: boolean;
    onClose: () => void;
    onConfirm: (val: any) => void;
    field: string;
    value: any;
    options?: string[];
}) => {
    const { t } = useTranslation();
    const [inputValue, setInputValue] = useState(value || '');
    const [oldPassword, setOldPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [showOldPassword, setShowOldPassword] = useState(false);
    const [showNewPassword, setShowNewPassword] = useState(false);
    const [isLoading, setIsLoading] = useState(false);

    React.useEffect(() => {
        setInputValue(value || '');
    }, [value, open]);

    // 为 PhoneInput 注入自定义样式
    React.useEffect(() => {
        if (open && field === 'phone') {
            const style = document.createElement('style');
            style.id = 'phone-input-custom-styles';
            style.textContent = `
                .react-phone-input-2 input[type="search"],
                .react-phone-input-2 .search-box {
                    background: red !important;
                    color: white !important;
                    border: 1px solid white !important;
                }
                .react-phone-input-2 ul li:hover,
                .react-phone-input-2 ul li.highlight {
                    background: red !important;
                    color: white !important;
                }
            `;
            document.head.appendChild(style);

            return () => {
                const existingStyle = document.getElementById('phone-input-custom-styles');
                if (existingStyle) {
                    document.head.removeChild(existingStyle);
                }
            };
        }
    }, [open, field]);

    // 处理确认操作
    const handleConfirmClick = async () => {
        setIsLoading(true);
        try {
            if (field === 'password') {
                await onConfirm({ oldPassword, newPassword });
            } else {
                await onConfirm(inputValue);
            }
        } finally {
            setIsLoading(false);
        }
    };

    if (!open) return null;

    return (
        <div
            className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-60"
            onClick={onClose}
        >
            <div
                className="bg-[rgb(28,25,23)] border border-[rgb(54,54,54)] rounded-2xl md:w-[25rem] w-[90%]  shadow-2xl p-6 "
                onClick={e => e.stopPropagation()}
            >
                <div className="text-lg font-bold mb-4 text-white tracking-wide">
                    {field === 'nickname' && t('settings.nickname')}
                    {field === 'email' && t('settings.email')}
                    {field === 'phone' && t('settings.phoneNumber')}
                    {field === 'gender' && t('settings.gender')}
                    {field === 'password' && t('settings.password')}
                </div>
                {/* 修改性别 和 修改昵称   */}
                {field === 'gender' ? (
                    <div className="relative mb-4">
                        <i className="fas fa-venus-mars border-[rgb(141,141,141)] absolute left-3 top-1/2 -translate-y-1/2 text-lg pointer-events-none" />
                        <select
                            className="w-full cursor-pointer border rounded-xl border-[white] bg-[rgb(28,25,23)] text-pink-100 pl-10 py-2 focus:outline-none focus:ring-2 focus:ring-pink-400 appearance-none"
                            style={{ minWidth: 0 }}
                            value={inputValue}
                            onChange={e => setInputValue(e.target.value)}
                        >
                            {options?.map(opt => (
                                <option key={opt} value={opt}>{t(`settings.genderTypes.${opt}`)}</option>
                            ))}
                        </select>
                    </div>
                ) :
                    // 修改密码 和 修改邮箱 
                    field === 'password' ? (
                        <>
                            <div className="relative mb-2">
                                <i className="fas fa-lock border-[rgb(141,141,141)] absolute left-3 top-1/2 -translate-y-1/2 text-lg pointer-events-none" />
                                {/* 旧密码  */}
                                <input
                                    type={showOldPassword ? 'text' : 'password'}
                                    className="w-full border rounded-xl border-[white] bg-[rgb(28,25,23)] text-pink-100 px-10 py-2 pr-10 focus:outline-none focus:ring-2 focus:ring-pink-400"
                                    placeholder={t('settings.password') + ' (' + t('settings.messages.oldPassword') + ')'}
                                    value={oldPassword}
                                    onChange={e => setOldPassword(e.target.value)}
                                />
                                {/* 显示旧密码 */}
                                <button
                                    type="button"
                                    className="absolute right-3 top-1/2 -translate-y-1/2 text-lg text-[226,225,225] focus:outline-none"
                                    tabIndex={-1}
                                    onClick={() => setShowOldPassword(v => !v)}
                                >
                                    <i className={showOldPassword ? 'fas fa-eye-slash' : 'fas fa-eye'} />
                                </button>
                            </div>
                            <div className="relative mb-4">
                                <i className="fas fa-lock border-[rgb(141,141,141)] absolute left-3 top-1/2 -translate-y-1/2 text-lg pointer-events-none" />
                                <input
                                    type={showNewPassword ? 'text' : 'password'}
                                    className="w-full border border-[white] bg-[rgb(28,25,23)] text-[226,225,225] rounded-xl px-10 py-2 pr-10 focus:outline-none focus:ring-2 focus:ring-pink-400"
                                    placeholder={t('settings.password') + ' (' + t('settings.messages.newPassword') + ')'}
                                    value={newPassword}
                                    onChange={e => setNewPassword(e.target.value)}
                                />
                                {/* 显示新密码 */}
                                <button
                                    type="button"
                                    className="absolute right-3 top-1/2 -translate-y-1/2 text-lg text-[226,225,225] focus:outline-none"
                                    tabIndex={-1}
                                    onClick={() => setShowNewPassword(v => !v)}
                                >
                                    <i className={showNewPassword ? 'fas fa-eye-slash' : 'fas fa-eye'} />
                                </button>
                            </div>
                        </>
                    ) : field === 'phone' ? (
                        <div className="relative mb-4">
                            <i className="fas fa-phone border-[rgb(141,141,141)] absolute left-3 top-1/2 -translate-y-1/2 text-lg pointer-events-none" />
                            <div className="phone-input-container">
                                <PhoneInput
                                    country={'cn'}
                                    value={inputValue}
                                    onChange={setInputValue}
                                    inputClass="!bg-[rgb(28,25,23)] !text-pink-100 !border-white !rounded-xl !pl-10"
                                    buttonClass="!bg-[rgb(28,25,23)]"

                                    dropdownClass="!bg-[rgb(33,37,41)]"
                                    containerClass="w-full"
                                    inputStyle={{
                                        width: '100%',
                                        background: 'rgb(28,25,23)',
                                        color: 'white',
                                        borderRadius: '0.75rem',
                                        border: '1px solid white',
                                        padding: '0.5rem 1rem',
                                        paddingLeft: '2.5rem'
                                    }}
                                    dropdownStyle={{
                                        background: 'rgb(33,37,41)',
                                        color: 'white',
                                        minWidth: '250px',
                                        zIndex: 9999
                                    }}
                                    placeholder={t('settings.phoneNumber')}
                                    enableSearch
                                    disableSearchIcon={false}
                                />
                            </div>
                        </div>
                    ) : field === 'email' ? (
                        <div className="relative mb-4">
                            <i className="fas fa-envelope border-[rgb(141,141,141)] absolute left-3 top-1/2 -translate-y-1/2 text-lg pointer-events-none" />
                            <input
                                className="w-full border border-[white] bg-[rgb(28,25,23)] text-pink-100 rounded-xl px-10 py-2 focus:outline-none focus:ring-2 focus:ring-pink-400"
                                value={inputValue}
                                onChange={e => setInputValue(e.target.value)}
                            />
                        </div>
                    ) : field === 'nickname' ? (
                        <div className="relative mb-4">
                            <i className="fas fa-user border-[rgb(141,141,141)] absolute left-3 top-1/2 -translate-y-1/2 text-lg pointer-events-none" />
                            <input
                                className="w-full border border-[white] bg-[rgb(28,25,23)] text-pink-100 rounded-xl px-10 py-2 focus:outline-none focus:ring-2 focus:ring-pink-400"
                                value={inputValue}
                                onChange={e => setInputValue(e.target.value)}
                            />
                        </div>
                    ) : (
                        <input
                            className="w-full border border-[white] bg-[rgb(28,25,23)] text-pink-100 rounded-xl px-3 py-2 mb-4 focus:outline-none focus:ring-2 focus:ring-pink-400"
                            value={inputValue}
                            onChange={e => setInputValue(e.target.value)}
                        />
                    )}
                <div className="flex justify-between mt-2">

                    <button
                        className={`w-[90%] m-auto px-4 py-2 rounded-xl text-white font-bold transition ${isLoading
                            ? 'bg-gray-500 cursor-not-allowed'
                            : 'bg-[rgb(231,82,117)] hover:opacity-90'
                            }`}
                        onClick={handleConfirmClick}
                        disabled={isLoading}
                    >
                        {isLoading ? (
                            <div className="flex items-center justify-center">
                                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                                {t('common.loading') || 'Loading...'}
                            </div>
                        ) : (
                            t('common.confirm')
                        )}
                    </button>
                </div>
            </div>
        </div>
    );
};

const ProfileSettings: React.FC<ProfileSettingsProps> = ({
    avatar, displayName, gender, email, phone, tokensBalance, membershipTier, onProfileUpdated
}) => {
    const defaultAvatar = '/assets/user-icons/man-f06d242ecbaa154c05843d8e91f779c41dbef390319247606b1919b87169c74a.svg';
    const showAvatar = avatar || defaultAvatar;
    const showEmail = email || '';
    const [nickname, setNickname] = useState(displayName == null ? '' : displayName);
    const [showGender, setShowGender] = useState(gender == null ? 'unknown' : gender);
    const [showPhone, setShowPhone] = useState(phone == null ? '' : phone);
    const password = '********';
    const { t, i18n } = useTranslation();
    const dynamicFonts = getDynamicFonts(i18n);
    const [modalOpen, setModalOpen] = useState(false);
    const [editField, setEditField] = useState<string>('');
    const [editValue, setEditValue] = useState<any>('');
    const [avatarModalOpen, setAvatarModalOpen] = useState(false);

    // 使用useUserProfile hook获取头像更新处理函数
    const { handleAvatarUpdated } = useUserProfile();

    React.useEffect(() => {
        setNickname(displayName || '');
    }, [displayName]);

    React.useEffect(() => {
        // 如果 gender 为 null 或 undefined，则显示 'unknown'
        setShowGender(gender == null ? 'unknown' : gender);
    }, [gender]);

    React.useEffect(() => {
        setShowPhone(phone || '');
    }, [phone]);

    // 打开编辑弹窗
    const handleEdit = (field: string, value: any) => {
        setEditField(field);
        setEditValue(value);
        setModalOpen(true);
    };
    // 关闭弹窗
    const handleClose = () => {
        setModalOpen(false);
    };
    // 确认编辑
    const handleConfirm = async (val: any) => {
        if (["nickname", "gender", "phone"].includes(editField)) {
            let payload: any = {};
            if (editField === "nickname") payload.displayName = val;
            if (editField === "gender") payload.gender = val;
            if (editField === "phone") payload.phone = val;
            try {
                const res = await updateUserInformation(payload);
                if (res?.data?.success) {
                    // 本地UI同步更新
                    if (editField === "nickname") setNickname(val);
                    if (editField === "gender") setShowGender(val);
                    if (editField === "phone") setShowPhone(val);
                    // 调用messageAPi组件通知 
                    message.success(t('settings.messages.updateSuccess'));
                    if (onProfileUpdated) onProfileUpdated(); // 通知父组件刷新
                } else {
                    message.error(t('settings.messages.updateFailed'));
                }
            } catch (e: any) {
                message.error(t('settings.messages.requestFailed'));
            }
            setModalOpen(false);
            return;
        }
        if (editField === "password") {
            try {
                const res = await updateUserPassword({
                    newPassWord: val.newPassword,
                    oldPassWord: val.oldPassword
                });
                if (res?.data?.success) {
                    message.success(t('settings.messages.passwordChangeSuccess'));
                    if (onProfileUpdated) onProfileUpdated(); // 密码修改后也可刷新
                } else {
                    message.error(t('settings.messages.passwordChangeFailed'));
                }
            } catch (e: any) {
                message.error(t('settings.messages.requestFailed'));
            }
            setModalOpen(false);
            return;
        }
        setModalOpen(false);
    };

    // 格式化token数量，只保留两位小数
    const formatTokens = (val?: string) => {
        if (!val) return '0.00';
        const num = Number(val);
        if (isNaN(num)) return '0.00';
        return num.toFixed(2);
    };

    // 头像装饰图片选择
    let badgeImg: string | null = null;
    if (membershipTier === 1) badgeImg = dj1;
    if (membershipTier === 2) badgeImg = dj2;
    if (membershipTier === 3) badgeImg = dj3;

    // 编辑后刷新
    const handleProfileUpdated = () => {
        // getuserInformation(); // This function is not defined in the original file, so it's commented out.
    };

    // 头像上传成功后的处理
    const handleAvatarUpdatedLocal = () => {
        if (onProfileUpdated) {
            onProfileUpdated();
        }
        // 同时调用从useUserProfile获取的头像更新函数
        handleAvatarUpdated();
    };


    return (
        <div className="w-full relative bg-zinc-900 rounded-[10px] border border-[#282828] mx-auto mb-5 md:mb-10">
            <div className="justify-start items-center w-full lg:inline-flex p-6 max-w-full">
                <div className="w-full md:w-[30%] md:max-w-[30%] flex flex-col items-center justify-center">
                    <div className="flex flex-col items-center justify-center w-full">
                        {/* 头像及装饰 */}
                        <div className="relative w-26 h-26 mb-3 flex items-center justify-center mx-auto">
                            <div
                                className="relative cursor-pointer group"
                                onClick={() => setAvatarModalOpen(true)}
                            >
                                <img className="w-24 h-24 rounded-full" src={showAvatar} alt="User Avatar" />
                                <div className="absolute inset-0 bg-black bg-opacity-50 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                    <i className="fas fa-camera text-white text-lg"></i>
                                </div>
                            </div>
                            {badgeImg && (
                                <img
                                    src={badgeImg}
                                    alt="badge"
                                    className="absolute w-16 h-16 -right-[2rem] -top-[2rem] md:w-20 md:h-20 md:right-[-3rem] md:top-[-2.5rem]"
                                    style={{
                                        transform: 'rotate(45deg)',
                                    }}
                                />
                            )}
                        </div>
                        {/* 我的token显示区 */}
                        <div style={{ fontFamily: dynamicFonts.font3}} className="flex flex-row items-center justify-center mt-2">
                            <div className="px-2 py-1 rounded-lg bg-gradient-to-r from-pink-500 via-red-400 to-yellow-400 shadow text-white font-semibold text-xs md:text-sm tracking-wide border border-pink-300 flex items-center" style={{ minWidth: '70px' }}>
                                {t('settings.myToken') || '我的Token'}
                                <div className="ml-2 text-xl font-extrabold text-transparen drop-shadow select-text flex items-center">
                                    {formatTokens(tokensBalance)}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className=" ml-4 justify-between lg:justify-start items-start lg:gap-[72px] lg:max-w-[70%] lg:w-[70%] flex mt-10 lg:mt-0">
                    <div className="flex-col justify-start items-start gap-4 inline-flex w-[calc(50%-18px)] max-w-[calc(50%-18px)] lg:w-[calc(50%-36px)] lg:max-w-[calc(50%-36px)]">
                        <div className="flex-col justify-start items-start gap-1 flex w-full max-w-full">
                            <div className="justify-start items-start gap-1.5 inline-flex">
                                <div style={{ fontFamily: dynamicFonts.font1 }} className="text-neutral-400 text-sm font-normal leading-tight">{t('settings.nickname')}</div>
                                <div className="w-5 h-5 p-1 rounded-[50px] border border-white/20 justify-center items-center flex">
                                    <div className="grow shrink basis-0 self-stretch p-[1.80px] justify-center items-center inline-flex">
                                        <div className="w-[10px] h-[10px] relative cursor-pointer" onClick={() => handleEdit('nickname', nickname)}>
                                            <img src={editIcon} alt={t('settings.edit')} />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div style={{ fontFamily: dynamicFonts.font3 }} className="text-white text-sm font-medium leading-normal w-full max-w-full truncate">{nickname || t('settings.notSet')}</div>
                        </div>

                        {/* 邮箱  */}
                        <div className="flex-col justify-start items-start gap-1 flex w-full max-w-full">
                            <div className="justify-start items-start gap-1.5 inline-flex">
                                <div style={{ fontFamily: dynamicFonts.font1 }} className="text-neutral-400 text-sm font-normal leading-tight">{t('settings.email')}</div>
                                {/* <div className="w-5 h-5 p-1 rounded-[50px] border border-white/20 justify-center items-center flex">
                                    <div className="grow shrink basis-0 self-stretch p-[1.80px] justify-center items-center inline-flex">
                                        <div className="w-[10px] h-[10px] relative cursor-pointer" onClick={() => handleEdit('email', showEmail)}>
                                            <img src={editIcon} alt={t('settings.edit')} />
                                        </div>
                                    </div>
                                </div> */}
                            </div>
                            <div style={{ fontFamily: dynamicFonts.font3 }} className="text-white text-sm font-medium leading-normal w-full max-w-full truncate">{showEmail}</div>
                        </div>

                        {/* <div className="flex-col justify-start items-start gap-1 flex w-full max-w-full">
                            <div className="justify-start items-start gap-1.5 inline-flex">
                                <div style={{ fontFamily: dynamicFonts.font1 }} className="text-neutral-400 text-sm font-normal leading-tight">{t('settings.phoneNumber')}</div>
                                <div className="w-5 h-5 p-1 rounded-[50px] border border-white/20 justify-center items-center flex">
                                    <div className="grow shrink basis-0 self-stretch p-[1.80px] justify-center items-center inline-flex">
                                        <div className="w-[10px] h-[10px] relative cursor-pointer" onClick={() => handleEdit('phone', showPhone)}>
                                            <img src={editIcon} alt={t('settings.edit')} />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div style={{ fontFamily: dynamicFonts.font3 }} className="text-white text-sm font-medium leading-normal w-full max-w-full truncate">{showPhone || t('settings.notSet')}</div>
                        </div> */}
                    </div>
                    <div className="flex-col justify-start items-start gap-4 inline-flex w-[calc(50%-36px)]">
                        <div className="flex-col justify-start items-start gap-1 flex w-full max-w-full">
                            <div className="justify-start items-start gap-1.5 inline-flex">
                                <div style={{ fontFamily: dynamicFonts.font1 }} className="text-neutral-400 text-sm font-normal leading-tight">{t('settings.gender')}</div>
                                <div className="w-5 h-5 p-1 rounded-[50px] border border-white/20 justify-center items-center flex">
                                    <div className="grow shrink basis-0 self-stretch p-[1.80px] justify-center items-center inline-flex">
                                        <div className="w-[10px] h-[10px] relative cursor-pointer" onClick={() => handleEdit('gender', showGender)}>
                                            <img src={editIcon} alt={t('settings.edit')} />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div style={{ fontFamily: dynamicFonts.font3 }} className="text-white text-sm font-medium leading-normal w-full max-w-full truncate">{t(`settings.genderTypes.${showGender?.toLowerCase?.() || 'unknown'}`)}</div>
                        </div>

                        <div className="flex-col justify-start items-start gap-1 flex w-full max-w-full">
                            <div className="justify-start items-start gap-1.5 inline-flex">
                                <div style={{ fontFamily: dynamicFonts.font1 }} className="text-neutral-400 text-sm font-normal leading-tight">{t('settings.password')}</div>
                                <div className="w-5 h-5 p-1 rounded-[50px] border border-white/20 justify-center items-center flex">
                                    <div className="grow shrink basis-0 self-stretch p-[1.80px] justify-center items-center inline-flex">
                                        <div className="w-[10px] h-[10px] relative cursor-pointer" onClick={() => handleEdit('password', '')}>
                                            <img src={editIcon} alt={t('settings.edit')} />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div style={{ fontFamily: dynamicFonts.font3 }} className="text-white text-sm font-medium leading-normal w-full max-w-full truncate">{password}</div>
                        </div>
                    </div>
                </div>
            </div>
            {/* 编辑弹窗 */}
            <EditModal
                open={modalOpen}
                onClose={handleClose}
                onConfirm={handleConfirm}
                field={editField}
                value={editField === 'gender' && (editValue == null ? 'unknown' : editValue)}
                options={editField === 'gender' ? ['male', 'female', 'other'] : undefined}
            />
            {/* 头像上传弹窗 */}
            <AvatarUploadModal
                open={avatarModalOpen}
                onClose={() => setAvatarModalOpen(false)}
                onSuccess={handleAvatarUpdatedLocal}
                currentAvatar={showAvatar}
            />
        </div>
    );
};

export default ProfileSettings; 